Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: default to fetch type in keyed mutator #2753

Merged
merged 3 commits into from
Sep 10, 2023

Conversation

linkvt
Copy link
Contributor

@linkvt linkvt commented Aug 21, 2023

Closes #2744

Hi,

as a few other also noticed the typings used in the bound mutator do not default anymore to the data type used in useSWR<ThisOne> and needs to be specified explicitly everytime right now.

Looking at the other types surrounding the KeyedMutator type it seems reasonable to default to the data type specified at useSWR<...>, e.g. as done here:

swr/_internal/src/types.ts

Lines 372 to 381 in e510955

export interface ScopedMutator {
/**
* @typeParam Data - The type of the data related to the key
* @typeParam MutationData - The type of the data returned by the mutator
*/
<Data = any, MutationData = Data>(
matcher: (key?: Arguments) => boolean,
data?: MutationData | Promise<MutationData> | MutatorCallback<MutationData>,
opts?: boolean | MutatorOptions<Data, MutationData>
): Promise<Array<MutationData | undefined>>

Let me know if and where a test could be added if you want to test the typings.

Thanks, Vincent

Copy link

@orca-security-us orca-security-us bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Orca Security Scan Summary

Status Check Issues by priority
passed Passed Secrets high 0  medium 0  low 0  info 0

@codesandbox-ci
Copy link

codesandbox-ci bot commented Aug 21, 2023

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

Latest deployment of this branch, based on commit 4b1bd9a:

Sandbox Source
SWR-Basic Configuration
SWR-States Configuration
SWR-Infinite Configuration
SWR-SSR Configuration

SSlime-s added a commit to SSlime-s/qtheme-v2 that referenced this pull request Sep 2, 2023
vercel/swr#2753
これが原因で type-check が落ちてた
治ったら上げる
@linkvt linkvt force-pushed the reuse-data-type-in-keyed-mutator branch from 2fb2d29 to f6761db Compare September 5, 2023 15:06
@linkvt
Copy link
Contributor Author

linkvt commented Sep 5, 2023

Hello @shuding or @huozhi , would you mind looking at this tiny PR fixing the types of a keyed mutator? I just rebased the code, let me know if something is missing here.
Thanks!

@huozhi
Copy link
Member

huozhi commented Sep 5, 2023

Hi, could you also add a types test for this case so we can avoid the regression later? Thanks

@promer94 promer94 force-pushed the reuse-data-type-in-keyed-mutator branch from 4d2b12e to 67dab71 Compare September 10, 2023 09:13
Copy link
Collaborator

@promer94 promer94 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you!

@promer94 promer94 force-pushed the reuse-data-type-in-keyed-mutator branch from 67dab71 to 4b1bd9a Compare September 10, 2023 09:50
@promer94 promer94 merged commit efe07d7 into vercel:main Sep 10, 2023
4 checks passed
mutate(async () => 1)

mutate(async () => 1, { populateCache: false })
// FIXME: this should work.
// mutate(async () => 1, { populateCache: false })
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@promer94 thanks for adding the test, maybe we should create an issue to follow up on this? it feels like a regression for mutate() API types

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The original pr #2708 did not fix this correctly so there is no regression here.

I also think we should not support this because the type implementation would be really complicated and not useful in practice. You should always make sure you data has same structure as cache when using the bounded mutate fn.

I just keep it here as a reference.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

right the type is number, I updated them in #2781

@linkvt linkvt deleted the reuse-data-type-in-keyed-mutator branch September 10, 2023 14:17
@AmirHosseinKarimi
Copy link

AmirHosseinKarimi commented Sep 24, 2023

Hey guys. Thanks for improving the SWR.
When we can have these changes on the new version?
Is there any routine release plan?

@huozhi
Copy link
Member

huozhi commented Sep 25, 2023

@AmirHosseinKarimi A few type improvements including this are landed in 2.2.3

renovate bot referenced this pull request in Unleash/unleash Oct 6, 2023
[![Mend
Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com)

This PR contains the following updates:

| Package | Change | Age | Adoption | Passing | Confidence |
|---|---|---|---|---|---|
| [swr](https://swr.vercel.app)
([source](https://togithub.com/vercel/swr)) | [`2.2.2` ->
`2.2.4`](https://renovatebot.com/diffs/npm/swr/2.2.2/2.2.4) |
[![age](https://developer.mend.io/api/mc/badges/age/npm/swr/2.2.4?slim=true)](https://docs.renovatebot.com/merge-confidence/)
|
[![adoption](https://developer.mend.io/api/mc/badges/adoption/npm/swr/2.2.4?slim=true)](https://docs.renovatebot.com/merge-confidence/)
|
[![passing](https://developer.mend.io/api/mc/badges/compatibility/npm/swr/2.2.2/2.2.4?slim=true)](https://docs.renovatebot.com/merge-confidence/)
|
[![confidence](https://developer.mend.io/api/mc/badges/confidence/npm/swr/2.2.2/2.2.4?slim=true)](https://docs.renovatebot.com/merge-confidence/)
|

---

### Release Notes

<details>
<summary>vercel/swr (swr)</summary>

### [`v2.2.4`](https://togithub.com/vercel/swr/releases/tag/v2.2.4)

[Compare
Source](https://togithub.com/vercel/swr/compare/v2.2.3...v2.2.4)

##### Patches

- Revert "Remove `index.js` suffix of `use-sync-external-store/shim` to
support React Native" by [@&#8203;huozhi](https://togithub.com/huozhi)
in
[https://github.com/vercel/swr/pull/2802](https://togithub.com/vercel/swr/pull/2802)

**Full Changelog**:
vercel/swr@v2.2.3...v2.2.4

### [`v2.2.3`](https://togithub.com/vercel/swr/releases/tag/v2.2.3)

[Compare
Source](https://togithub.com/vercel/swr/compare/v2.2.2...v2.2.3)

##### Patches

- fix: remove permissive type by
[@&#8203;wcatron](https://togithub.com/wcatron) in
[https://github.com/vercel/swr/pull/2759](https://togithub.com/vercel/swr/pull/2759)
- Remove `index.js` suffix of `use-sync-external-store/shim` to support
React Native by [@&#8203;malash](https://togithub.com/malash) in
[https://github.com/vercel/swr/pull/2767](https://togithub.com/vercel/swr/pull/2767)
- fix: default to fetch type in keyed mutator by
[@&#8203;linkvt](https://togithub.com/linkvt) in
[https://github.com/vercel/swr/pull/2753](https://togithub.com/vercel/swr/pull/2753)
- types: export mutation types by
[@&#8203;promer94](https://togithub.com/promer94) in
[https://github.com/vercel/swr/pull/2780](https://togithub.com/vercel/swr/pull/2780)

##### Misc

- test: update tests, use matched types for mutate api by
[@&#8203;huozhi](https://togithub.com/huozhi) in
[https://github.com/vercel/swr/pull/2781](https://togithub.com/vercel/swr/pull/2781)

##### New Contributors

- [@&#8203;wcatron](https://togithub.com/wcatron) made their first
contribution in
[https://github.com/vercel/swr/pull/2759](https://togithub.com/vercel/swr/pull/2759)
- [@&#8203;malash](https://togithub.com/malash) made their first
contribution in
[https://github.com/vercel/swr/pull/2767](https://togithub.com/vercel/swr/pull/2767)
- [@&#8203;linkvt](https://togithub.com/linkvt) made their first
contribution in
[https://github.com/vercel/swr/pull/2753](https://togithub.com/vercel/swr/pull/2753)

**Full Changelog**:
vercel/swr@v2.2.2...v2.2.3

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined),
Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the
rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update
again.

---

- [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check
this box

---

This PR has been generated by [Mend
Renovate](https://www.mend.io/free-developer-tools/renovate/). View
repository job log
[here](https://developer.mend.io/github/Unleash/unleash).

<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzNy4wLjMiLCJ1cGRhdGVkSW5WZXIiOiIzNy4wLjMiLCJ0YXJnZXRCcmFuY2giOiJtYWluIn0=-->

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
| Promise<MutationData | undefined>
| MutatorCallback<MutationData>,
export type KeyedMutator<Data> = <MutationData = Data>(
data?: Data | Promise<Data | undefined> | MutatorCallback<Data>,
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@promer94 Why was this change reverted? It makes the generic completely useless and returning different MutationData to be passed to populateCache impossible with proper types.

This probably needs to be overload based to function properly, otherwise MutationData will just be inferred improperly from the data arg, although it is mostly possible to do without overloads with some rather extensive types:

type KeyedMutator<Data> = <MutationData = Data>(data?: MutationData | Promise<MutationData | undefined> | MutatorCallback<MutationData>, opts?: boolean | Omit<MutatorOptions<Data, MutationData>, 'populateCache'> & (MutationData extends Data ? Pick<MutatorOptions<Data, Data>, 'populateCache'> : { populateCache: Exclude<MutatorOptions<Data, MutationData>['populateCache'], boolean> })) => Promise<Data | MutationData | undefined>;

I have tested the above and it works as expected, except in the case where opts is not passed or is a boolean. This is why I suggested the overload approach, since if options is not passed as an object, typescript doesn't enforce it being passed.

@simenbrekken-visma
Copy link

simenbrekken-visma commented Nov 17, 2023

Not sure if I understood the above changes completely, but after upgrading from 2.0.3 to 2.2.3 we had to update all our populateCache methods:

Before (2.0.3)

const { data = [], mutate } = useSWR<ListItem[]>('/api/list', fetcher);

const addListItem = (name: string) => {
    mutate(
        async () => {
            const item: ListItem = await createListItem(name);

            return item;
        },
        {
            populateCache: (result, currentData = []) => [
                ...currentData,
                result,
            ],
        },
    );
};

After (2.2.3)

const { data = [], mutate } = useSWR<ListItem[]>('/api/list', fetcher);

const addListItem = (name: string) => {
    mutate(
        async () => {
            const item: ListItem = await createListItem(name);

            return [item];
        },
        {
            populateCache: (result, currentData = []) => [
                ...currentData,
                ...result,
            ],
        },
    );
};

We may have missed a generic that can be passed to work around this, but having to modify our mutators to return the same type as given to useSWR feels a bit clunky.

renovate bot referenced this pull request in huv1k/website Jan 12, 2024
[![Mend
Renovate](https://app.renovatebot.com/images/banner.svg)](https://renovatebot.com)

This PR contains the following updates:

| Package | Change | Age | Adoption | Passing | Confidence |
|---|---|---|---|---|---|
| [swr](https://swr.vercel.app)
([source](https://togithub.com/vercel/swr)) | [`2.2.2` ->
`2.2.4`](https://renovatebot.com/diffs/npm/swr/2.2.2/2.2.4) |
[![age](https://developer.mend.io/api/mc/badges/age/npm/swr/2.2.4?slim=true)](https://docs.renovatebot.com/merge-confidence/)
|
[![adoption](https://developer.mend.io/api/mc/badges/adoption/npm/swr/2.2.4?slim=true)](https://docs.renovatebot.com/merge-confidence/)
|
[![passing](https://developer.mend.io/api/mc/badges/compatibility/npm/swr/2.2.2/2.2.4?slim=true)](https://docs.renovatebot.com/merge-confidence/)
|
[![confidence](https://developer.mend.io/api/mc/badges/confidence/npm/swr/2.2.2/2.2.4?slim=true)](https://docs.renovatebot.com/merge-confidence/)
|

---

### Release Notes

<details>
<summary>vercel/swr (swr)</summary>

### [`v2.2.4`](https://togithub.com/vercel/swr/releases/tag/v2.2.4)

[Compare
Source](https://togithub.com/vercel/swr/compare/v2.2.3...v2.2.4)

##### Patches

- Revert "Remove `index.js` suffix of `use-sync-external-store/shim` to
support React Native" by [@&#8203;huozhi](https://togithub.com/huozhi)
in
[https://github.com/vercel/swr/pull/2802](https://togithub.com/vercel/swr/pull/2802)

**Full Changelog**:
vercel/swr@v2.2.3...v2.2.4

### [`v2.2.3`](https://togithub.com/vercel/swr/releases/tag/v2.2.3)

[Compare
Source](https://togithub.com/vercel/swr/compare/v2.2.2...v2.2.3)

##### Patches

- fix: remove permissive type by
[@&#8203;wcatron](https://togithub.com/wcatron) in
[https://github.com/vercel/swr/pull/2759](https://togithub.com/vercel/swr/pull/2759)
- Remove `index.js` suffix of `use-sync-external-store/shim` to support
React Native by [@&#8203;malash](https://togithub.com/malash) in
[https://github.com/vercel/swr/pull/2767](https://togithub.com/vercel/swr/pull/2767)
- fix: default to fetch type in keyed mutator by
[@&#8203;linkvt](https://togithub.com/linkvt) in
[https://github.com/vercel/swr/pull/2753](https://togithub.com/vercel/swr/pull/2753)
- types: export mutation types by
[@&#8203;promer94](https://togithub.com/promer94) in
[https://github.com/vercel/swr/pull/2780](https://togithub.com/vercel/swr/pull/2780)

##### Misc

- test: update tests, use matched types for mutate api by
[@&#8203;huozhi](https://togithub.com/huozhi) in
[https://github.com/vercel/swr/pull/2781](https://togithub.com/vercel/swr/pull/2781)

##### New Contributors

- [@&#8203;wcatron](https://togithub.com/wcatron) made their first
contribution in
[https://github.com/vercel/swr/pull/2759](https://togithub.com/vercel/swr/pull/2759)
- [@&#8203;malash](https://togithub.com/malash) made their first
contribution in
[https://github.com/vercel/swr/pull/2767](https://togithub.com/vercel/swr/pull/2767)
- [@&#8203;linkvt](https://togithub.com/linkvt) made their first
contribution in
[https://github.com/vercel/swr/pull/2753](https://togithub.com/vercel/swr/pull/2753)

**Full Changelog**:
vercel/swr@v2.2.2...v2.2.3

</details>

---

### Configuration

📅 **Schedule**: Branch creation - At any time (no schedule defined),
Automerge - At any time (no schedule defined).

🚦 **Automerge**: Enabled.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the
rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update
again.

---

- [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check
this box

---

This PR has been generated by [Mend
Renovate](https://www.mend.io/free-developer-tools/renovate/). View
repository job log
[here](https://developer.mend.io/github/huv1k/website).

<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiIzNy4xMjcuMCIsInVwZGF0ZWRJblZlciI6IjM3LjEyNy4wIiwidGFyZ2V0QnJhbmNoIjoibWFzdGVyIn0=-->

Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Mutate typescript
6 participants